package com.atguigu.gmall.common.exception;


import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author A
 * @version 1.0
 * @description: TODO
 * @date 2024/9/8 23:51
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {
    @Value(value = "${spring.application.name}" )
    private String serviceName;
    //业务异常处理器
    @ExceptionHandler(GmallException.class)
    public Result gmallException(GmallException e){
        log.info("全局捕获业务异常: {}"+e);
        Result<Object> fail = Result.fail();
        fail.setCode(e.getCode());
        fail.setMessage(e.getMessage());
        //RequestContextHolder利用ThreadLocal将请求放入当前线程
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        StringBuffer url = request.getRequestURL();
        Map<String, String[]> parameterMap = request.getParameterMap();
        HashMap<String, Object> map = new HashMap<>();
        map.put("path",url);
        map.put("params",parameterMap);
        map.put("serviceName",serviceName);
        fail.setData(map);
        return fail;
    }

    @ExceptionHandler(Exception.class)
    public Result otherException(Exception e){
        log.info("全局捕获系统异常: {}"+e);
        Result<Object> fail = Result.fail();
        fail.setCode(500);
        fail.setMessage("系统内部异常");
        return fail;
    }
}
